/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ie.tcd.cs.railtickets.commons.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;


/**
 *
 * @author Wenbo Sun
 */
public class NetUtil {

    public static Object sendObject(String ip, int port, Object object) throws IOException, ClassNotFoundException {
        Socket socket = new Socket(ip, port);
        return sendObject(socket, object);
    }

    public static Object sendObject(Socket socket, Object object) throws IOException, ClassNotFoundException {
        OutputStream os = socket.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(object);
        os.flush();
        InputStream is = socket.getInputStream();
        ObjectInputStream ois = new ObjectInputStream(is);
        return ois.readObject();
    }

    public static void simpleSendObject(Socket socket, Object object) throws IOException, ClassNotFoundException {
        OutputStream os = socket.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(object);
        oos.flush();
        os.flush();
        socket.close();
    }

}
